package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.JuXiangHuaCallBackUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 聚享花APIB回调
 */
@Service
public class JuXiangHuaApiBApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    MerchantThirdBaseInfoMapper merchantThirdBaseInfoMapper;

    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String apiCode = pushApiKeyParam.getApiCode();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("name",memberSourceInfo.getRealname());
        bizMap.put("mobile_md5",memberSourceInfo.getMobileMd5().toLowerCase());
        bizMap.put("id_card","");
        String city = memberSourceInfo.getCity();
        if (StrUtil.endWith(city, "市")) { city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1); }
        bizMap.put("city",city);
        bizMap.put("car", JuXiangHuaCallBackUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("gongjijin", JuXiangHuaCallBackUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("shebao", JuXiangHuaCallBackUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("house", JuXiangHuaCallBackUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("baodan_is", JuXiangHuaCallBackUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("credit_card", JuXiangHuaCallBackUtil.getXinyongka(memberSourceInfo.getXinyongka()));
        bizMap.put("isbankpay", 1);
        bizMap.put("job", JuXiangHuaCallBackUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("age",memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 0 : 1);
        bizMap.put("money", JuXiangHuaCallBackUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("ip", JuXiangHuaCallBackUtil.getReqIp(memberSourceInfo.getReqIp()));
        bizMap.put("time", System.currentTimeMillis() / 1000);
        bizMap.put("zhima_score", JuXiangHuaCallBackUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("education", JuXiangHuaCallBackUtil.getXueli(memberSourceInfo.getXueli()));
        bizMap.put("business_license", 1);
        bizMap.put("overdue", JuXiangHuaCallBackUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("huabei", JuXiangHuaCallBackUtil.getHuabei(memberSourceInfo.getHuabei()));
        bizMap.put("baitiao", JuXiangHuaCallBackUtil.getBaitiao(memberSourceInfo.getBaitiao()));

        String apiSecret = pushApiKeyParam.getApiSecret();
        String body = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("source", apiCode);
        paramMap.put("data", body);

        log.info("【聚享花下游APIB半流程】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【聚享花下游APIB半流程】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code),"200")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String apiCode = pushApiKeyParam.getApiCode();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("name",memberSourceInfo.getRealname());
        bizMap.put("mobile",memberSourceInfo.getMobile());
        String city = memberSourceInfo.getCity();
        if (StrUtil.endWith(city, "市")) { city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1); }
        bizMap.put("city",city);
        bizMap.put("car", JuXiangHuaCallBackUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("gongjijin", JuXiangHuaCallBackUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("shebao", JuXiangHuaCallBackUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("house", JuXiangHuaCallBackUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("baodan_is", JuXiangHuaCallBackUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("credit_card", JuXiangHuaCallBackUtil.getXinyongka(memberSourceInfo.getXinyongka()));
        bizMap.put("isbankpay", 1);
        bizMap.put("job", JuXiangHuaCallBackUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("age",memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 0 : 1);
        bizMap.put("money", JuXiangHuaCallBackUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("ip", JuXiangHuaCallBackUtil.getReqIp(memberSourceInfo.getReqIp()));
        bizMap.put("time", System.currentTimeMillis() / 1000);
        bizMap.put("zhima_score", JuXiangHuaCallBackUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("education", JuXiangHuaCallBackUtil.getXueli(memberSourceInfo.getXueli()));
        bizMap.put("business_license", 1);
        bizMap.put("overdue", JuXiangHuaCallBackUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("huabei", JuXiangHuaCallBackUtil.getHuabei(memberSourceInfo.getHuabei()));
        bizMap.put("baitiao", JuXiangHuaCallBackUtil.getBaitiao(memberSourceInfo.getBaitiao()));

        String apiSecret = pushApiKeyParam.getApiSecret();
        String body = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("source", apiCode);
        paramMap.put("data", body);

        log.info("【聚享花下游APIB半流程】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);

        log.info("【聚享花下游APIB半流程】导单结束【result】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("message");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code),"200")) {
            JSONObject jsonObject1 = resultObject.getJSONObject("data");
            String url1 = jsonObject1.getString("url");
            String orderSn = jsonObject1.getString("order_sn");
            pushApiResult.setApproveUrl(url1);
            pushApiResult.setOutOrderNo(orderSn);
            pushApiResult.setPushSuccess(true);
            return pushApiResult;
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
        noticeParamDTO.setQueryResult(paramContent);

        JSONObject jsonObject = JSON.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObject)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }
        String orderNo = jsonObject.getString("order_sn");
        noticeParamDTO.setOutOrderNo(orderNo);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(orderNo));

        if (ObjectUtil.isEmpty(entityByOutOrderNoLock) || PushStatusEnum.SUCCESS.getValue().equals(entityByOutOrderNoLock.getStatus())){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
        }

        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "回调成功");
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

}
